<!DOCTYPE html>

<html>
  <head>
      <meta charset="UTF-8">
      <title>监听子组件事件</title>
      <link rel="stylesheet" href="/stylesheets/bootstrap.min.css">
      <style>
          .border {
              margin: 10px auto ;
          }
          .kfm-border {
              border-top: 1px solid #007bff ;
              border-bottom: 1px solid #007bff ;
          }
      </style>
      <script src="/javascripts/vue@3.0.11.js" ></script>
  </head>
  <body>

    <div class="container" id="app">
        <!-- 使用自定义组件 -->
        <cart-item @increase="increaseHandler" @reduce="reduceHandler"></cart-item>
        <cart-item @increase="increaseHandler" @reduce="reduceHandler"></cart-item>
        <div>{{message}}</div>
    </div>

    <script>
        const app = Vue.createApp({
            data(){
                return { message:'' }
            },
            methods: {
                increaseHandler(value){
                    console.log( value );
                    this.message = value ;
                },
                reduceHandler( value ){
                    console.log( value );
                    this.message = value ;
                }
            }
        });

        app.component( 'CartItem' , {
            data(){
                return { id: 2002 , name:'明矾米线' , price: 18 , num: 1 }
            },
            template: `<div class="row border">
                            <span class="col-2">{{id}}</span>
                            <span class="col-2">{{name}}</span>
                            <span class="col-2">{{price}}</span>
                            <span class="col-3">
                                <div class="btn-group">
                                  <a type="button" class="btn btn-primary btn-sm" @click="jian">-</a>
                                  <a type="button" class="btn btn-sm kfm-border">{{num}}</a>
                                  <a type="button" class="btn btn-primary btn-sm" @click="jia">+</a>
                                </div>
                            </span>
                       </div>`,
            methods: {
                jian(){
                    if( this.num > 1 ) {
                        this.num--;
                        // 触发自定义事件
                        this.$emit( 'reduce' , this.price * this.num );
                    }
                },
                jia(){
                    this.num++ ;
                    // 触发自定义事件
                    this.$emit( 'increase' , this.price * this.num );
                }
            }
        });

        app.mount( '#app' );
    </script>

  </body>
</html>